package com.genius.framework.multitenancy.config;

import com.genius.framework.multitenancy.constants.TenantConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * feign client 之间的调用添加头部信息
 */
public class MultiTenancyFeignClientConfig {

    private static final Logger logger = LoggerFactory.getLogger(MultiTenancyFeignClientConfig.class);

    @Bean(name = "multiTenancyFeignClientInterceptor")
    public RequestInterceptor getMultiTenancyFeignClientInterceptor() throws IOException {
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate template) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    String tenantId = request.getHeader(TenantConstants.REQUEST_HEADER_TENANT_FLAG);
                    tenantId = tenantId == null || "".equals(tenantId) ? TenantConstants.DEFAULT_TENANT_ID : tenantId;
                    template.header(TenantConstants.REQUEST_HEADER_TENANT_FLAG, tenantId);
                }
            }
        };
    }
}
